<template>
  <div class="blog-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1>博客文章管理</h1>
      <el-button type="primary" @click="handleCreate" :icon="Plus">
        写新文章
      </el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <el-card shadow="never">
        <div class="filter-content">
          <el-input
            v-model="searchParams.keywords"
            placeholder="搜索文章标题、内容或摘要..."
            prefix-icon="Search"
            clearable
            style="width: 300px"
            @keyup.enter="handleSearch"
            @clear="handleSearchClear"
          />
          <div class="filter-right">
            <el-select
              v-model="searchParams.status"
              placeholder="状态筛选"
              clearable
            >
              <el-option label="草稿" value="draft" />
              <el-option label="已发布" value="published" />
              <el-option label="已归档" value="archived" />
              <el-option label="私有" value="private" />
            </el-select>
            <el-select
              v-model="searchParams.commentStatus"
              placeholder="评论状态"
              clearable
            >
              <el-option label="开启" :value="1" />
              <el-option label="关闭" :value="0" />
            </el-select>
            <el-select
              v-model="searchParams.isTop"
              placeholder="置顶状态"
              clearable
            >
              <el-option label="置顶" :value="1" />
              <el-option label="普通" :value="0" />
            </el-select>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 博客文章表格 -->
    <el-card shadow="never">
      <el-table
        :data="blogList"
        v-loading="loading"
        :border="true"
        :stripe="true"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column label="文章信息" min-width="350">
          <template #default="scope">
            <div class="blog-title-cell">
              <span class="title-text">{{ scope.row.title }}</span>
              <el-tag
                v-if="scope.row.isTop"
                size="small"
                type="warning"
                style="margin-left: 8px"
              >
                置顶
              </el-tag>
            </div>
            <div class="blog-meta-info">
              <span class="slug">Slug: {{ scope.row.slug }}</span>
              <span class="excerpt">{{
                getExcerpt(scope.row.excerpt || scope.row.content)
              }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="统计信息" width="120">
          <template #default="scope">
            <div class="stats-info">
              <div>浏览: {{ scope.row.viewCount }}</div>
              <div>点赞: {{ scope.row.likeCount }}</div>
              <div>字数: {{ scope.row.wordCount }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="分类" width="100">
          <template #default="scope">
            <el-tag>{{ getCategoryName(scope.row.categoryId) }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="scope">
            <div class="status-cell">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
              <el-tag
                v-if="scope.row.commentStatus"
                size="small"
                type="success"
                style="margin-left: 4px"
              >
                评论开
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="时间信息" width="180">
          <template #default="scope">
            <div class="time-info">
              <div>创建: {{ formatDate(scope.row.createdAt) }}</div>
              <div>更新: {{ formatDate(scope.row.updatedAt) }}</div>
              <div v-if="scope.row.publishedAt">
                发布: {{ formatDate(scope.row.publishedAt) }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleEdit(scope.row)"
              :icon="Edit"
              :disabled="scope.row.isDeleted"
            >
              编辑
            </el-button>
            <el-button
              link
              type="success"
              @click="handleView(scope.row)"
              :icon="View"
            >
              查看
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="暂无文章数据" />
        </template>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedBlogs.length > 0">
        <el-alert title="已选择文章" type="info" :closable="false" show-icon>
          <template #default>
            <span>已选择 {{ selectedBlogs.length }} 篇文章</span>
            <el-button
              link
              type="primary"
              @click="handleBatchPublish"
              style="margin-left: 16px"
            >
              批量发布
            </el-button>
            <el-button
              link
              type="success"
              @click="handleBatchToggleComment"
              style="margin-left: 8px"
            >
              批量切换评论
            </el-button>
            <el-button
              link
              type="warning"
              @click="handleBatchToggleTop"
              style="margin-left: 8px"
            >
              批量置顶
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleBatchDelete"
              style="margin-left: 8px"
            >
              批量删除
            </el-button>
            <el-button link @click="clearSelection" style="margin-left: 8px">
              清空选择
            </el-button>
          </template>
        </el-alert>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Edit, Delete, View } from "@element-plus/icons-vue";
import { blogApi } from "@/api/blog";
import { categoryApi } from "@/api/category";

const router = useRouter();

// 响应式数据
const loading = ref(false);
const blogList = ref([]);
const selectedBlogs = ref([]);
const categoryList = ref([]);

// 搜索参数
const searchParams = reactive({
  keywords: "",
  status: "",
  commentStatus: null,
  isTop: null,
  categoryId: null,
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 辅助方法
const getExcerpt = (content, length = 60) => {
  if (!content) return "";
  return content.length > length
    ? content.substring(0, length) + "..."
    : content;
};

const formatDate = (dateString) => {
  if (!dateString) return "-";
  return new Date(dateString).toLocaleString("zh-CN");
};

const getStatusType = (status) => {
  const types = {
    published: "success",
    draft: "info",
    archived: "warning",
    private: "danger",
  };
  return types[status] || "info";
};

const getStatusText = (status) => {
  const texts = {
    published: "已发布",
    draft: "草稿",
    archived: "已归档",
    private: "私有",
  };
  return texts[status] || "未知";
};

const getCategoryName = (categoryId) => {
  const category = categoryList.value.find((c) => c.id === categoryId);
  return category ? category.name : "未分类";
};

// API 调用方法
const loadBlogs = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchParams,
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === "" || params[key] === null) {
        delete params[key];
      }
    });

    const response = await blogApi.getBlogs(params);
    blogList.value = response.data.records || [];
    pagination.total = response.data.total || 0;
  } catch (error) {
    console.error("加载博客列表失败:", error);
    ElMessage.error("加载博客列表失败");
  } finally {
    loading.value = false;
  }
};

const loadCategories = async () => {
  try {
    const response = await categoryApi.getCategories();
    categoryList.value = response.data || [];
  } catch (error) {
    console.error("加载分类列表失败:", error);
    ElMessage.error("加载分类列表失败");
  }
};

const deleteBlog = async (blogId) => {
  try {
    await blogApi.deleteBlog(blogId);
    ElMessage.success("删除成功");
    // await loadBlogs();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败");
  }
};

const batchDeleteBlogs = async (blogIds, permanent = false) => {
  try {
    if (permanent) {
      await blogApi.batchDeleteBlogsPermanent(blogIds);
    } else {
      await blogApi.batchDeleteBlogs(blogIds);
    }
    ElMessage.success("批量删除成功");
    clearSelection();
    await loadBlogs();
  } catch (error) {
    console.error("批量删除失败:", error);
    ElMessage.error("批量删除失败");
  }
};

const batchPublishBlogs = async (blogIds) => {
  try {
    await blogApi.batchPublishBlogs(blogIds);
    ElMessage.success("批量发布成功");
    clearSelection();
    await loadBlogs();
  } catch (error) {
    console.error("批量发布失败:", error);
    ElMessage.error("批量发布失败");
  }
};

const batchToggleCommentStatus = async (blogIds) => {
  try {
    await blogApi.batchToggleCommentStatus(blogIds);
    ElMessage.success("批量切换评论状态成功");
    clearSelection();
    await loadBlogs();
  } catch (error) {
    console.error("批量切换评论状态失败:", error);
    ElMessage.error("批量切换评论状态失败");
  }
};

const batchToggleTopStatus = async (blogIds) => {
  try {
    await blogApi.batchToggleTopStatus(blogIds);
    ElMessage.success("批量切换置顶状态成功");
    clearSelection();
    await loadBlogs();
  } catch (error) {
    console.error("批量切换置顶状态失败:", error);
    ElMessage.error("批量切换置顶状态失败");
  }
};

// 事件处理方法
const handleSelectionChange = (selection) => {
  selectedBlogs.value = selection;
};

const clearSelection = () => {
  selectedBlogs.value = [];
};

const handleSearch = () => {
  pagination.currentPage = 1;
  loadBlogs();
};

const handleSearchClear = () => {
  searchParams.keywords = "";
  handleSearch();
};

const handleReset = () => {
  searchParams.keywords = "";
  searchParams.status = "";
  searchParams.commentStatus = null;
  searchParams.isTop = null;
  searchParams.categoryId = null;
  handleSearch();
};

const handleCreate = () => {
  router.push("/blog/edit");
};

const handleEdit = (blog) => {
  if (blog.isDeleted) {
    ElMessage.warning("无法编辑已删除的文章");
    return;
  }
  router.push(`/blog/edit/${blog.id}`);
};

// const handleView = (blog) => {
//   router.push(`/blog/detail/${blog.id}`);
// };

const handleView = async (blog) => {
  await blogApi.getBlog(blog.id);
};

const handleDelete = async (blog) => {
  try {
    await ElMessageBox.confirm(`确定要删除文章"${blog.title}"吗`);
    await deleteBlog(blog.id);
  } catch {
    console.log(error);
    ElMessage.error("删除失败");
  }
};

const handleBatchDelete = async () => {
  if (selectedBlogs.value.length === 0) {
    ElMessage.warning("请先选择要删除的文章");
    return;
  }

  const hasDeleted = selectedBlogs.value.some((blog) => blog.isDeleted);
  const actionText = hasDeleted ? "永久删除" : "删除";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}选中的 ${selectedBlogs.value.length} 篇文章吗？${
        hasDeleted ? "此操作将彻底删除数据，不可恢复！" : ""
      }`,
      `批量${actionText}确认`,
      {
        confirmButtonText: `确定${actionText}`,
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const blogIds = selectedBlogs.value.map((blog) => blog.id);
    await batchDeleteBlogs(blogIds, hasDeleted);
  } catch {
    // 用户取消删除
  }
};

const handleBatchPublish = async () => {
  if (selectedBlogs.value.length === 0) {
    ElMessage.warning("请先选择要发布的文章");
    return;
  }

  // 过滤掉已删除的文章
  const validBlogs = selectedBlogs.value.filter((blog) => !blog.isDeleted);
  if (validBlogs.length === 0) {
    ElMessage.warning("选中的文章均为已删除状态，无法发布");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要发布选中的 ${validBlogs.length} 篇文章吗？`,
      "批量发布确认",
      {
        confirmButtonText: "确定发布",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const blogIds = validBlogs.map((blog) => blog.id);
    await batchPublishBlogs(blogIds);
  } catch {
    // 用户取消发布
  }
};

const handleBatchToggleComment = async () => {
  if (selectedBlogs.value.length === 0) {
    ElMessage.warning("请先选择要操作的文章");
    return;
  }

  const validBlogs = selectedBlogs.value.filter((blog) => !blog.isDeleted);
  if (validBlogs.length === 0) {
    ElMessage.warning("选中的文章均为已删除状态，无法操作");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要切换选中的 ${validBlogs.length} 篇文章的评论状态吗？`,
      "批量切换评论状态确认",
      {
        confirmButtonText: "确定切换",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const blogIds = validBlogs.map((blog) => blog.id);
    await batchToggleCommentStatus(blogIds);
  } catch {
    // 用户取消操作
  }
};

const handleBatchToggleTop = async () => {
  if (selectedBlogs.value.length === 0) {
    ElMessage.warning("请先选择要操作的文章");
    return;
  }

  const validBlogs = selectedBlogs.value.filter((blog) => !blog.isDeleted);
  if (validBlogs.length === 0) {
    ElMessage.warning("选中的文章均为已删除状态，无法操作");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要切换选中的 ${validBlogs.length} 篇文章的置顶状态吗？`,
      "批量切换置顶状态确认",
      {
        confirmButtonText: "确定切换",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const blogIds = validBlogs.map((blog) => blog.id);
    await batchToggleTopStatus(blogIds);
  } catch {
    // 用户取消操作
  }
};

const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  loadBlogs();
};

const handlePageChange = (newPage) => {
  pagination.currentPage = newPage;
  loadBlogs();
};

// 生命周期
onMounted(() => {
  loadBlogs();
  loadCategories();
});
</script>

<style scoped>
.blog-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.blog-title-cell {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.title-text {
  font-weight: 600;
  color: #303133;
}

.blog-meta-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.slug {
  font-size: 12px;
  color: #909399;
}

.excerpt {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

.stats-info {
  font-size: 12px;
  color: #606266;
  line-height: 1.6;
}

.status-cell {
  display: flex;
  align-items: center;
}

.time-info {
  font-size: 12px;
  color: #606266;
  line-height: 1.6;
}

.batch-actions {
  margin: 16px 0;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-content {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .filter-right {
    justify-content: space-between;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .blog-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>
